import type { IPath } from '@/interfaces';
import type { QueryKey } from '@tanstack/query-core';
import type { TError, TMetadata } from '@/types';
import { queryPath } from '@/services/api';
import { useQuery } from '@tanstack/react-query';

export default function useUser(
  queryKey?: QueryKey | TMetadata,
  initialData?: IPath
) {
  const rootPath = '/paths';
  let qKey;
  if (queryKey) {
    if ('all' in queryKey) {
      qKey = queryKey.all['page'].k;
      initialData = queryKey.all['page'].v as IPath;
    } else {
      qKey = queryKey[0] === rootPath ? queryKey : [rootPath, ...queryKey];
    }
  } else {
    qKey = [rootPath, '/'];
  }

  return useQuery<IPath, TError>(
    qKey,
    async (context) => {
      return (await queryPath({
        query: {
          name: context.queryKey[1],
        },
      })) as IPath;
    },
    {
      initialData,
    }
  );
}
